#include "system.h"


// 定义一个 System 对象
System_t xtp_system;

/**
 * 状态LED闪烁
*/
void state_led() {
	static uint8_t count = 0;
    xtp_system.StateLed.state_led_count++;
	
	switch(xtp_system.PtcState)
	{
		case PTC_RUNNING:
			break;
		case PTC_STOPPING:
			if (count >= 5)
			{
				gpio_bits_write(STATE_LED_GPIOX, STATE_LED_PIN, FALSE); // LED 灭
				if (xtp_system.StateLed.state_led_count>1000) {
					count = 0;
					xtp_system.StateLed.state_led_count = 0;
					xtp_system.StateLed.bit_led_toggle_flag = 0;
				}
			}
			if (xtp_system.StateLed.state_led_count > 200 && count < 5)
			{
				xtp_system.StateLed.bit_led_toggle_flag ^= 1;
				xtp_system.StateLed.state_led_count = 0;
				gpio_bits_write(STATE_LED_GPIOX, STATE_LED_PIN, (confirm_state)xtp_system.StateLed.bit_led_toggle_flag);
				count++;
			}
			break;
		case PTC_ON:
			gpio_bits_write(STATE_LED_GPIOX, STATE_LED_PIN, TRUE);
			break;
		case PTC_OFF:
			gpio_bits_write(STATE_LED_GPIOX, STATE_LED_PIN, FALSE);
			break;
	}
}

/**
 * 设置状态LED闪烁频率周期
*/
void set_freq(uint32_t period_ms)
{
    xtp_system.StateLed.state_led_ms_flag = period_ms;
}

/**
 * 初始化 System
*/
void xtp_system_init(System_t *system)
{
    /* GPIO 初始化 */
	gpio_init_type gpio_init_struct;
	/* 使能 STATE_LED 外设时钟 */
    crm_periph_clock_enable(STATE_CRM_PERIPH_CLOCK, TRUE);

    /* 设置默认参数 */
    gpio_default_para_init(&gpio_init_struct);
	
	/* 配置 GPIO 参数 */
    gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER; /* 较大电流推动/吸入能力 */
    gpio_init_struct.gpio_out_type = GPIO_OUTPUT_OPEN_DRAIN; /* 开漏输出 */
    gpio_init_struct.gpio_mode = GPIO_MODE_OUTPUT;
    gpio_init_struct.gpio_pins = STATE_LED_PIN;
    gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
    gpio_init(STATE_LED_GPIOX, &gpio_init_struct);


    /* StateLed 结构体初始化 */
    system->StateLed.bit_led_on_off = 0;
    system->StateLed.bit_led_toggle_flag = 0;
    system->StateLed.state_led_count = 0;
    system->StateLed.state_led_ms_flag = 500;
    system->StateLed.state_led = state_led;
    system->StateLed.set_freq = set_freq;
	
    system->PtcState = PTC_STOPPING;
}


